package com.zycx.system.role.service;

import com.zycx.common.entity.EntityUtils;
import com.zycx.interceptor.CurrentUser;
import com.zycx.common.result.ServerResponse;
import com.zycx.system.role.entity.Role;
import com.zycx.system.role.mapper.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Description:
 * Created by zycx on 2018-12-11 20:39
 * Created with IntelliJ IDEA.
 */
@Service
@Slf4j
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    public ServerResponse saveRole(Role role) {
        if (role == null) {
            return ServerResponse.errorMessage("对象不能为空");
        }
        role.setId(EntityUtils.getId());
        role.setCtrTime(new Date());
        role.setCtrUserId(CurrentUser.getUserID());
        role.setCtrUserName(CurrentUser.getName());
        int insert = roleMapper.insert(role);
        if (insert == 0) {
            return ServerResponse.error();
        }
        return ServerResponse.successData(role);
    }


    public ServerResponse getRoleById(String id) {
        if (StringUtils.isEmpty(id)) {
            return ServerResponse.errorMessage("id  不能为空");
        }
        Role role = roleMapper.selectByPrimaryKey(id);
        if (role == null) {
            return ServerResponse.errorMessage("数据不存在");
        }
        return ServerResponse.successData(role);
    }

    public ServerResponse putRole(Role role) {
        if (role == null) {
            return ServerResponse.errorMessage("数据不能为空");
        }
        if (StringUtils.isEmpty(role.getId())) {
            return ServerResponse.errorMessage("id 不能为空");
        }
        Role one = roleMapper.selectByPrimaryKey(role.getId());
        one.setRoleName(role.getRoleName());
        one.setRemark(role.getRemark());
        one.setUpTime(new Date());
        one.setUpUserName(CurrentUser.getName());
        one.setUpUserId(CurrentUser.getUserID());
        int i = roleMapper.updateByPrimaryKey(one);
        if (i == 0) {
            return ServerResponse.error();
        }
        return ServerResponse.successData(one);
    }

    public ServerResponse deleteRoleById(String id) {
        if (StringUtils.isEmpty(id)) {
            return ServerResponse.errorMessage("id 不能为空");
        }
        Role role = roleMapper.selectByPrimaryKey(id);
        if (role == null) {
            return ServerResponse.errorMessage("数据不存在,请刷新数据");
        }
        role.setEnable(false);
        int i = roleMapper.updateByPrimaryKey(role);
        if (i == 0) {
            return ServerResponse.error();
        }
        return ServerResponse.success();
    }

}
